using System.Drawing;
using System.Windows.Forms;
using BLGenerator.BusinessLogic;

namespace BLGenerator
{
    public partial class ProjectSettingsForm : Form
    {
        private readonly BusinessLogic.Project _project;

        public ProjectSettingsForm(BusinessLogic.Project project)
        {
            _project = project;
            InitializeComponent();
        }

        #region Helper methods

        protected void AlignButtons()
        {
            int witdh = pnlButtons.ClientSize.Width;
            int buttonOffset = 10;
            btnCancel.Left = witdh / 2 - btnCancel.Width - buttonOffset;
            btnOk.Left = witdh / 2 + buttonOffset;
        }

        protected void CloseForm()
        {
            Close();
        }

        protected void FillControlsFromSettings()
        {
            tableSettings.Controls.Clear();
            tableSettings.RowStyles.Clear();
            tableSettings.RowCount = _project.Settings.Length;
            int i = 0;
            foreach (ProjectSetting setting in _project.Settings)
            {
                Label label = new Label();
                label.Text = setting.Name;
                label.Dock = DockStyle.Fill;
                label.TextAlign = ContentAlignment.MiddleRight;
                tableSettings.Controls.Add(label, 0, i);
                Control newControl = setting.GetControl();
                newControl.Name = setting.Name;
                setting.FillControl(newControl, _project.SettingValues[setting.Name]);
                tableSettings.Controls.Add(newControl, 2, i);
                tableSettings.RowStyles.Add(new System.Windows.Forms.RowStyle(SizeType.AutoSize));
                i++;
            }
        }

        protected void FillSettingsFromControls()
        {
            foreach (ProjectSetting setting in _project.Settings)
            {
                object value = setting.GetSetting(tableSettings.Controls[setting.Name]);
                _project.SettingValues[setting.Name] = value;
            }
        }

        #endregion

        #region Event handlers

        private void ProjectSettingsForm_Load(object sender, System.EventArgs e)
        {
            FillControlsFromSettings();
        }

        private void ProjectSettingsForm_Resize(object sender, System.EventArgs e)
        {
            AlignButtons();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            CloseForm();
        }

        private void btnOk_Click(object sender, System.EventArgs e)
        {
            _project.IsModified = true;
            FillSettingsFromControls();
            CloseForm();
        }

        private void ProjectSettingsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseForm();
        }

        #endregion

    }
}